﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;
using HaterAide.Interfaces;
using HaterAide.Mappings;
using HaterAide.SQL.DataClasses.Objects;
using HaterAide.SQL.Interfaces.SQL;
using HaterAide.SQL.SQLServer.Statements;
using Utilities.SQL;
using Utilities.SQL.DataClasses;
using Utilities.SQL.DataClasses.Enums;

#endregion

namespace HaterAide.SQL.SQLServer
{
    /// <summary>
    /// Internal class used for building the SQL
    /// </summary>
    internal static class SQLBuilder
    {
        #region Public Functions

        public static List<T> SelectWhere<T>(string ConnectionString, IClass TempClassDefinition, IClassManager ClassManager,
            IMappingManager MappingManager, IClause<T> Clause, IClause<T> OrderBy, Session CurrentSession, int Start, int End)
        {
            if (TempClassDefinition != null)
            {
                return Statements.SelectWhere.Run<T>(ConnectionString, TempClassDefinition, ClassManager, MappingManager, Clause, OrderBy, CurrentSession, Start, End);
            }
            return new List<T>();
        }

        public static List<T> SelectAll<T>(string ConnectionString, IClass TempClassDefinition, IClassManager ClassManager,
            IMappingManager MappingManager, Session CurrentSession)
        {
            if (TempClassDefinition != null)
            {
                return Statements.SelectAll.Run<T>(ConnectionString, TempClassDefinition, ClassManager, MappingManager, CurrentSession);
            }
            return new List<T>();
        }

        public static List<T> SelectListByID<T>(string ConnectionString, object IDValue, IClass InputClassDefinition,
            IClass OutputClassDefinition, IClassManager ClassManager, IMappingManager MappingManager,
            string FieldName, Session CurrentSession)
        {
            if (InputClassDefinition != null && OutputClassDefinition != null)
            {
                return SelectManyToMany.Run<T>(ConnectionString, IDValue, InputClassDefinition, OutputClassDefinition, ClassManager, MappingManager, FieldName, CurrentSession);
            }
            return new List<T>();
        }

        public static T SelectByID<T>(string ConnectionString, object IDValue, IClassManager ClassManager,
            IMappingManager MappingManager, Session CurrentSession)
        {
            Type ObjectType = typeof(T);
            if (MappingManager.ClassMappings.ContainsKey(ObjectType))
            {
                return Select.Run<T>(ConnectionString, IDValue, ClassManager, MappingManager, CurrentSession);
            }
            return default(T);
        }

        public static bool Save(string ConnectionString, object Object, IClassManager ClassManager,
            IMappingManager MappingManager, Session CurrentSession)
        {
            using (SQLHelper Helper = new SQLHelper("", ConnectionString, CommandType.StoredProcedure))
            {
                try
                {
                    Helper.Open();
                    Helper.BeginTransaction();
                    List<Utilities.DataTypes.Pair<object, IEnumerable>> Commands = new List<Utilities.DataTypes.Pair<object, IEnumerable>>();
                    IEnumerable<Command> TempCommands = null;
                    if (Object is IEnumerable)
                    {
                        IEnumerable ObjectList = (IEnumerable)Object;
                        foreach (object TempObject in ObjectList)
                        {
                            Type ObjectType = TempObject.GetType();
                            IAttributeMap ClassMapping = null;
                            while (!MappingManager.ClassMappings.ContainsKey(ObjectType))
                            {
                                ObjectType = ObjectType.BaseType;
                            }
                            ClassMapping = MappingManager.ClassMappings[ObjectType];
                            if (TempObject is IHaterAideObject
                                && ((IHaterAideObject)TempObject).Update0)
                            {
                                TempCommands = Update.GetCommands(TempObject, ClassManager, MappingManager, Helper);
                            }
                            else
                            {
                                TempCommands = Insert.GetCommands(TempObject, ClassManager, MappingManager, Helper);
                            }
                            Commands.Add(new Utilities.DataTypes.Pair<object, IEnumerable>(TempObject, TempCommands));
                        }
                    }
                    else
                    {
                        Type ObjectType = Object.GetType();
                        IAttributeMap ClassMapping = null;
                        while (!MappingManager.ClassMappings.ContainsKey(ObjectType))
                        {
                            ObjectType = ObjectType.BaseType;
                        }
                        ClassMapping = MappingManager.ClassMappings[ObjectType];
                        if (Object is IHaterAideObject
                            && ((IHaterAideObject)Object).Update0)
                        {
                            TempCommands = Update.GetCommands(Object, ClassManager, MappingManager, Helper);
                        }
                        else
                        {
                            TempCommands = Insert.GetCommands(Object, ClassManager, MappingManager, Helper);
                        }
                        Commands.Add(new Utilities.DataTypes.Pair<object, IEnumerable>(Object, TempCommands));
                    }
                    foreach (Utilities.DataTypes.Pair<object, IEnumerable> TempPair in Commands)
                    {
                        object TempObject = TempPair.Left;
                        Type ObjectType = TempObject.GetType();
                        IAttributeMap ClassMapping = null;
                        while (!MappingManager.ClassMappings.ContainsKey(ObjectType))
                        {
                            ObjectType = ObjectType.BaseType;
                        }
                        ClassMapping = MappingManager.ClassMappings[ObjectType];
                        foreach (Command Command in TempPair.Right)
                        {
                            Helper.Command = Command.StoredProcedure;
                            foreach (Variable Variable in Command.Variables)
                            {
                                Variable.SetupSQL(Helper);
                            }
                            if (Command.CommandType == Enums.CommandType.Scaler)
                            {
                                object IDValue = Helper.ExecuteScalar();
                                if (ClassMapping.IDProperties[0].AutoIncrement)
                                {
                                    Utilities.Reflection.Reflection.SetValue(IDValue, TempObject, ClassMapping.IDProperties[0].Name, "");
                                }
                            }
                            else if (Command.CommandType == Enums.CommandType.NonQuery)
                            {
                                Helper.ExecuteNonQuery();
                            }
                        }
                    }
                    Helper.Commit();
                }
                catch { throw; }
                finally { Helper.Close(); }
            }
            return true;
        }

        public static void SetupFunctions(Database Database)
        {
            Database.AddFunction("Split", "CREATE FUNCTION dbo.Split(@List nvarchar(2000),@SplitOn nvarchar(5)) RETURNS @ReturnValue table(Id int identity(1,1),Value nvarchar(100)) AS  BEGIN While (Charindex(@SplitOn,@List)>0) Begin Insert Into @ReturnValue (value) Select Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1))) Set @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List)) End Insert Into @ReturnValue (Value) Select Value = ltrim(rtrim(@List)) Return END");
        }

        public static void SetupStoredProcedures(Database Database)
        {
            foreach (HaterAide.SQL.DataClasses.Table Table in Database.Tables)
            {
                Insert.SetupInsertStoredProcedure(Table);
                Update.SetupUpdateStoredProcedure(Table);
                SetupDeleteStoredProcedure(Table);
                SetupDeleteByForeignKeyStoredProcedure(Table);
                SetupSelectStoredProcedure(Table);
                SetupSelectAllStoredProcedure(Table);
                SetupSelectAllByForeignKeyStoredProcedure(Table);
            }
        }

        public static void SetupAuditTables(Database Database)
        {
            List<Table> TempTables = new List<Table>();
            foreach (HaterAide.SQL.DataClasses.Table Table in Database.Tables)
            {
                TempTables.Add(SetupAuditTables(Table));
                SetupInsertUpdateTrigger(Table);
                SetupDeleteTrigger(Table);
            }
            Database.Tables.AddRange(TempTables);
        }

        public static void Delete(string ConnectionString, object Object, IClass ClassDefinition,
            IAttributeMap ClassMapping, IClassManager ClassManager, IMappingManager MappingManager,
            Session CurrentSession)
        {
            List<Command> Commands = new List<Command>();
            if (Object is IEnumerable)
            {
                IEnumerable ObjectList = (IEnumerable)Object;
                foreach (object TempObject in ObjectList)
                {
                    Type ObjectType = TempObject.GetType();
                    while (!MappingManager.ClassMappings.ContainsKey(ObjectType))
                    {
                        ObjectType = ObjectType.BaseType;
                    }
                    ClassDefinition = ClassManager[ObjectType];
                    ClassMapping = MappingManager.ClassMappings[ObjectType];
                    Commands.AddRange(Statements.Delete.GetCommands(TempObject, ClassDefinition, ClassMapping, ClassManager, MappingManager));
                }
            }
            else
            {
                Commands.AddRange(Statements.Delete.GetCommands(Object, ClassDefinition, ClassMapping, ClassManager, MappingManager));
            }
            using (SQLHelper Helper = new SQLHelper("", ConnectionString, CommandType.StoredProcedure))
            {
                try
                {
                    Helper.Open();
                    Helper.BeginTransaction();
                    foreach (Command Command in Commands)
                    {
                        Helper.Command = Command.StoredProcedure;
                        foreach (Variable Variable in Command.Variables)
                        {
                            Variable.SetupSQL(Helper);
                        }
                        if (Command.CommandType == Enums.CommandType.NonQuery)
                        {
                            Helper.ExecuteNonQuery();
                        }
                    }
                    Helper.Commit();
                }
                catch { throw; }
                finally { Helper.Close(); }
            }
        }

        public static List<T> SelectStoredProcedure<T>(string ConnectionString, IClass TempClassDefinition, IClassManager ClassManager, IMappingManager MappingManager, string StoredProcedureName, List<IVariable> Variables, Session CurrentSession)
        {
            if (TempClassDefinition != null)
            {
                return Statements.SelectStoredProcedure.Run<T>(ConnectionString, TempClassDefinition, ClassManager, MappingManager, StoredProcedureName, Variables, CurrentSession);
            }
            return new List<T>();
        }

        public static List<T> SelectSQLText<T>(string ConnectionString, IClass TempClassDefinition, IClassManager ClassManager, IMappingManager MappingManager, string SQLText, List<IVariable> Variables, Session CurrentSession)
        {
            if (TempClassDefinition != null)
            {
                return Statements.SelectSQLText.Run<T>(ConnectionString, TempClassDefinition, ClassManager, MappingManager, SQLText, Variables, CurrentSession);
            }
            return new List<T>();
        }

        #endregion

        #region Private Functions

        private static void SetupDeleteTrigger(HaterAide.SQL.DataClasses.Table Table)
        {
            StringBuilder Columns = new StringBuilder();
            StringBuilder Builder = new StringBuilder();
            Builder.Append("CREATE TRIGGER dbo.").Append(Table.Name).Append("_Audit_D ON dbo.")
                .Append(Table.Name).Append(" FOR DELETE AS IF @@rowcount=0 RETURN")
                .Append(" INSERT INTO dbo.").Append(Table.Name).Append("Audit").Append("(");
            string Splitter = "";
            foreach (Column Column in Table.Columns)
            {
                Columns.Append(Splitter).Append(Column.Name);
                Splitter = ",";
            }
            Builder.Append(Columns.ToString());
            Builder.Append(",AuditType) SELECT ");
            Builder.Append(Columns.ToString());
            Builder.Append(",'D' FROM deleted");
            Table.AddTrigger(Table.Name + "_Audit_D", Builder.ToString(), (int)TriggerType.INSERT);
        }

        private static void SetupInsertUpdateTrigger(HaterAide.SQL.DataClasses.Table Table)
        {
            StringBuilder Columns = new StringBuilder();
            StringBuilder Builder = new StringBuilder();
            Builder.Append("CREATE TRIGGER dbo.").Append(Table.Name).Append("_Audit_IU ON dbo.")
                .Append(Table.Name).Append(" FOR INSERT,UPDATE AS IF @@rowcount=0 RETURN declare @AuditType")
                .Append(" char(1) declare @DeletedCount int SELECT @DeletedCount=count(*) FROM DELETED IF @DeletedCount=0")
                .Append(" BEGIN SET @AuditType='I' END ELSE BEGIN SET @AuditType='U' END")
                .Append(" INSERT INTO dbo.").Append(Table.Name).Append("Audit").Append("(");
            string Splitter = "";
            foreach (Column Column in Table.Columns)
            {
                Columns.Append(Splitter).Append(Column.Name);
                Splitter = ",";
            }
            Builder.Append(Columns.ToString());
            Builder.Append(",AuditType) SELECT ");
            Builder.Append(Columns.ToString());
            Builder.Append(",@AuditType FROM inserted");
            Table.AddTrigger(Table.Name + "_Audit_IU", Builder.ToString(), (int)TriggerType.INSERT);
        }

        private static HaterAide.SQL.DataClasses.Table SetupAuditTables(HaterAide.SQL.DataClasses.Table Table)
        {
            HaterAide.SQL.DataClasses.Table AuditTable = new HaterAide.SQL.DataClasses.Table(Table.Name + "Audit", Table.ParentDatabase);
            AuditTable.AddColumn("ID", SqlDbType.Int.ToString(), 0, false, true, true, true, false, "", "", "");
            AuditTable.AddColumn("AuditType", SqlDbType.NVarChar.ToString(), 1, false, false, false, false, false, "", "", "");
            foreach (HaterAide.SQL.DataClasses.Column Column in Table.Columns)
            {
                AuditTable.AddColumn(Column.Name, Column.DataType.ToString(), Column.Length, Column.Nullable, false, false, false, false, "", "", "");
            }
            return AuditTable;
        }


        private static void SetupDeleteByForeignKeyStoredProcedure(HaterAide.SQL.DataClasses.Table Table)
        {
            foreach (HaterAide.SQL.DataClasses.Column Column in Table.Columns)
            {
                if (Column.ForeignKey.Count > 0)
                {
                    StringBuilder Builder = new StringBuilder();
                    if (Table.Name.EndsWith("_"))
                    {
                        Builder.Append("CREATE PROCEDURE dbo.").Append(Table.Name).Append("Delete_By_").Append(Column.Name).Append(" ");
                    }
                    else
                    {
                        Builder.Append("CREATE PROCEDURE dbo.").Append(Table.Name).Append("_Delete_By_").Append(Column.Name).Append(" ");
                    }
                    StringBuilder ColumnList = new StringBuilder();
                    StringBuilder ValueDefinition = new StringBuilder();

                    ValueDefinition.Append("@").Append(Column.Name).Append(" ")
                        .Append(Column.DataType.ToString());
                    if (Column.DataType == SqlDbType.NVarChar)
                    {
                        if (Column.Length == -1 || Column.Length == 5000)
                        {
                            ValueDefinition.Append("(MAX)");
                        }
                        else
                        {
                            ValueDefinition.Append("(").Append(Column.Length).Append(")");
                        }
                    }
                    ColumnList.Append(Column.Name).Append("=@").Append(Column.Name);
                    Builder.Append(ValueDefinition.ToString());
                    Builder.Append(" AS DELETE FROM ").Append(Table.Name).Append(" WHERE ");
                    Builder.Append(ColumnList.ToString());
                    if (Table.Name.EndsWith("_"))
                    {
                        Table.ParentDatabase.AddStoredProcedure(Table.Name + "Delete_By_" + Column.Name, Builder.ToString());
                    }
                    else
                    {
                        Table.ParentDatabase.AddStoredProcedure(Table.Name + "_Delete_By_" + Column.Name, Builder.ToString());
                    }
                }
            }
        }

        private static void SetupSelectAllByForeignKeyStoredProcedure(HaterAide.SQL.DataClasses.Table Table)
        {
            foreach (HaterAide.SQL.DataClasses.Column Column in Table.Columns)
            {
                if (Column.ForeignKey.Count > 0)
                {
                    StringBuilder Builder = new StringBuilder();
                    if (Table.Name.EndsWith("_"))
                    {
                        Builder.Append("CREATE PROCEDURE dbo.").Append(Table.Name).Append("Select_By_").Append(Column.Name).Append(" ");
                    }
                    else
                    {
                        Builder.Append("CREATE PROCEDURE dbo.").Append(Table.Name).Append("_Select_By_").Append(Column.Name).Append(" ");
                    }
                    StringBuilder ColumnList = new StringBuilder();
                    StringBuilder ValueDefinition = new StringBuilder();

                    ValueDefinition.Append("@").Append(Column.Name).Append(" ")
                        .Append(Column.DataType.ToString());
                    if (Column.DataType == SqlDbType.NVarChar)
                    {
                        if (Column.Length == -1 || Column.Length == 5000)
                        {
                            ValueDefinition.Append("(MAX)");
                        }
                        else
                        {
                            ValueDefinition.Append("(").Append(Column.Length).Append(")");
                        }
                    }
                    ColumnList.Append(Column.Name).Append("=@").Append(Column.Name);
                    Builder.Append(ValueDefinition.ToString());
                    Builder.Append(" AS SELECT * FROM ").Append(Table.Name).Append(" WHERE ");
                    Builder.Append(ColumnList.ToString());
                    if (Table.Name.EndsWith("_"))
                    {
                        Table.ParentDatabase.AddStoredProcedure(Table.Name + "Select_By_" + Column.Name, Builder.ToString());
                    }
                    else
                    {
                        Table.ParentDatabase.AddStoredProcedure(Table.Name + "_Select_By_" + Column.Name, Builder.ToString());
                    }
                }
            }
        }

        private static void SetupSelectAllStoredProcedure(HaterAide.SQL.DataClasses.Table Table)
        {
            StringBuilder Builder = new StringBuilder();
            if (Table.Name.EndsWith("_"))
            {
                Builder.Append("CREATE PROCEDURE dbo.").Append(Table.Name).Append("Select_All ");
            }
            else
            {
                Builder.Append("CREATE PROCEDURE dbo.").Append(Table.Name).Append("_Select_All ");
            }
            Builder.Append(" AS SELECT * FROM ").Append(Table.Name);
            if (Table.Name.EndsWith("_"))
            {
                Table.ParentDatabase.AddStoredProcedure(Table.Name + "Select_All", Builder.ToString());
            }
            else
            {
                Table.ParentDatabase.AddStoredProcedure(Table.Name + "_Select_All", Builder.ToString());
            }
        }

        private static void SetupSelectStoredProcedure(HaterAide.SQL.DataClasses.Table Table)
        {
            StringBuilder Builder = new StringBuilder();
            if (Table.Name.EndsWith("_"))
            {
                Builder.Append("CREATE PROCEDURE dbo.").Append(Table.Name).Append("Select ");
            }
            else
            {
                Builder.Append("CREATE PROCEDURE dbo.").Append(Table.Name).Append("_Select ");
            }
            StringBuilder ColumnList = new StringBuilder();
            StringBuilder ValueDefinition = new StringBuilder();
            string Splitter = "";
            string DefinitionSplitter = "";
            foreach (HaterAide.SQL.DataClasses.Column Column in Table.Columns)
            {
                if (Column.PrimaryKey)
                {
                    ValueDefinition.Append(DefinitionSplitter).Append("@").Append(Column.Name).Append(" ")
                        .Append(Column.DataType.ToString());
                    if (Column.DataType == SqlDbType.NVarChar)
                    {
                        if (Column.Length == -1 || Column.Length == 5000)
                        {
                            ValueDefinition.Append("(MAX)");
                        }
                        else
                        {
                            ValueDefinition.Append("(").Append(Column.Length).Append(")");
                        }
                    }
                    ColumnList.Append(Splitter).Append(Column.Name).Append("=@").Append(Column.Name);
                    Splitter = " AND ";
                    DefinitionSplitter = ",";
                }
            }
            Builder.Append(ValueDefinition.ToString());
            Builder.Append(" AS SELECT * FROM ").Append(Table.Name).Append(" WHERE ");
            Builder.Append(ColumnList.ToString());
            if (Table.Name.EndsWith("_"))
            {
                Table.ParentDatabase.AddStoredProcedure(Table.Name + "Select", Builder.ToString());
            }
            else
            {
                Table.ParentDatabase.AddStoredProcedure(Table.Name + "_Select", Builder.ToString());
            }
        }

        private static void SetupDeleteStoredProcedure(HaterAide.SQL.DataClasses.Table Table)
        {
            StringBuilder Builder = new StringBuilder();
            if (Table.Name.EndsWith("_"))
            {
                Builder.Append("CREATE PROCEDURE dbo.").Append(Table.Name).Append("Delete ");
            }
            else
            {
                Builder.Append("CREATE PROCEDURE dbo.").Append(Table.Name).Append("_Delete ");
            }
            StringBuilder ColumnList = new StringBuilder();
            StringBuilder ValueDefinition = new StringBuilder();
            string Splitter = "";
            string DefinitionSplitter = "";
            foreach (HaterAide.SQL.DataClasses.Column Column in Table.Columns)
            {
                if (Column.PrimaryKey)
                {
                    ValueDefinition.Append(DefinitionSplitter).Append("@").Append(Column.Name).Append(" ")
                        .Append(Column.DataType.ToString());
                    if (Column.DataType == SqlDbType.NVarChar)
                    {
                        if (Column.Length == -1 || Column.Length == 5000)
                        {
                            ValueDefinition.Append("(MAX)");
                        }
                        else
                        {
                            ValueDefinition.Append("(").Append(Column.Length).Append(")");
                        }
                    }
                    ColumnList.Append(Splitter).Append(Column.Name).Append("=@").Append(Column.Name);
                    Splitter = " AND ";
                    DefinitionSplitter = ",";
                }
            }
            Builder.Append(ValueDefinition.ToString());
            Builder.Append(" AS DELETE FROM ").Append(Table.Name).Append(" WHERE ");
            Builder.Append(ColumnList.ToString());
            if (Table.Name.EndsWith("_"))
            {
                Table.ParentDatabase.AddStoredProcedure(Table.Name + "Delete", Builder.ToString());
            }
            else
            {
                Table.ParentDatabase.AddStoredProcedure(Table.Name + "_Delete", Builder.ToString());
            }
        }

        #endregion

        #region Internal Functions

        internal static System.Collections.Generic.IEnumerable<DataClasses.Objects.Command> GetSaveCommands(object Object, IClassManager ClassManager, IMappingManager MappingManager, SQLHelper Helper)
        {
            if (Object is IHaterAideObject
                && ((IHaterAideObject)Object).Update0)
            {
                return Update.GetCommands(Object, ClassManager, MappingManager, Helper);
            }
            return Insert.GetCommands(Object, ClassManager, MappingManager, Helper);
        }

        internal static System.Collections.Generic.IEnumerable<DataClasses.Objects.Command> GetDeleteCommands(object Object, IClassManager ClassManager, IMappingManager MappingManager)
        {
            Type ObjectType = Object.GetType();
            while (!MappingManager.ClassMappings.ContainsKey(ObjectType))
            {
                ObjectType = ObjectType.BaseType;
            }
            IAttributeMap ClassMapping = MappingManager.ClassMappings[ObjectType];
            IClass ClassDefinition = ClassManager[ObjectType];
            return Statements.Delete.GetCommands(Object, ClassDefinition, ClassMapping, ClassManager, MappingManager);
        }

        #endregion
    }
}